<?php

require_once '../library/MAPI/AlloCine.php';
require_once "MainController.php";

/**
 * Contrôleur par défaut
 *
 * @package Controller
 * @author  nroche <nicolas.roche42@gmail.com>
 *
 */
class MediaController extends MainController {

    /**
     * Affichage du formulaire
     *
     * @return null
     */
    public function indexAction() {

        // .js
        $this->view->headScript()->appendFile($this->view->baseUrl() . "/js/mediasearch/mediasearch.js");
    }

    /**
     * Recherche de film
     * GET: q=...
     *
     * @return null
     */
    public function searchAction() {

        $params = $this->_request->getParams();

        if (!isset($params['title'])) {
            $this->_response->clearBody();
            $this->_response->clearHeaders();
            $this->_response->setHttpResponseCode(406);
            return;
        }
        $param_title = $params['title'];
        $param_sort = isset($params['sort']) ? $params['sort'] : 'title';
        $param_order = isset($params['order']) ? $params['order'] : 'desc';

        // FIXME: mettre en app.ini
        $movie_cache_allow = true;
        $movie_cache_max = 3;

        // FILMS
        if ($movie_cache_allow) {
            if (isset($_SESSION['mediaglobe']['movies'][$param_title]))
                $finalResults = $_SESSION['mediaglobe']['movies'][$param_title];
            else {
                $finalResults = $this->searchMovies($param_title);
                if (count($_SESSION['mediaglobe']['movies']) > $movie_cache_max)
                    array_pop($_SESSION['mediaglobe']['movies']);
                $_SESSION['mediaglobe']['movies'][$param_title] = $finalResults;
            }
        }
        else
            $finalResults = $this->searchMovies($param_title);

        $this->_helper->json($finalResults);
    }

    /**
     *
     * @param string $title
     */
    private function searchMovies($title) {

        $options = Zend_Registry::get('Zend_Config');
        $pluginName = $options['movie_plugin'];
        $plugin = 'MAPI_' . $options['movie_plugin'];

        // Recherche via l'API
        $api = new $plugin();
        $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
        if (isset($options['proxy'])){
            $api_params['proxy'] = $options['proxy'];
        }
        $api->setParams($api_params);
        $apiMovies = $api->searchMovies($title);

        if (count($apiMovies) > 100)
            throw new Exception('too many');

        if ($pluginName == 'TMDB') { // test

            // Recherche dans la DB
            $titleParts = explode (' ' , $title); // TODO : Gerer 2 espaces
            $movieMapper = new App_Model_Map_Movie();
            $dbMovies = $movieMapper->getMoviesByTitle($titleParts); // contient des array(idMovie, api_idMovie, avgRating)

            // On complete $apiMovies avec les $dbMovies communs
            $finalResults = array();
            foreach ($apiMovies as $apiMovie) { // MAPI_Model_Movie
                $apiMovie->movieIdInDB = -1;
                foreach ($dbMovies as $dbMovie) { // array(idMovie, api_idMovie,, api avgRating)
                    if ($dbMovie['api_idMovie'] == 'TMDB' && $apiMovie->id == $dbMovie['api_idMovie']) {
                        $apiMovie->avgRating = $dbMovie['avgRating'];
                        $apiMovie->movieIdInDB = $dbMovie['idMovie'];
                    }
                }
//                 $finalResults[] = $apiMovie;
                $finalResults[] = array(
                    'api_name' => 'TMDB',
                    'api_idMovie' => $apiMovie->id,
                    'title' => $apiMovie->o_title,
                    'titleFr' => $apiMovie->title,
                    'year' => $apiMovie->production_year,
                    'movieIdInDB' => $apiMovie->movieIdInDB,
                );
            }

            // On joint $dbMovie
            foreach ($dbMovies as $dbMovie) { // array(idMovie, api_idMovie,, api avgRating)
                $found = false;
                foreach ($finalResults as $result) { // MAPI_Model_Movie
                    if ($dbMovie['api'] == 'TMDB' && $result['api_idMovie'] == $dbMovie['api_idMovie']) {
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    $newMovie = array(
                        'api_name' => null,
                        'api_idMovie' => null,
                        'title' => 'COUCOU_FIXME',
                        'titleFr' => 'COUCOU_FIXME',
                        'year' => '',
                        'movieIdInDB' => $apiMovie->movieIdInDB,

                        'idMovieDB' => $dbMovie['idMovie'],
                        'avgRating' => $dbMovie['avgRating'],
                    );
                    $finalResults[] = $newMovie;
                }
            }
        }
        return $finalResults;
    }

    /**
     *     FIXME gerer le nom de l'api en plus de l'id
     *
     * Recuperation des details d'un film
     * GET: api_id=...
     */
    public function getdetailsAction() {

        $params = $this->_request->getParams();
        if (!isset($params['api_id'])) {
            $this->_response->clearBody();
            $this->_response->clearHeaders();
            $this->_response->setHttpResponseCode(406);
            return;
        }

        $options = Zend_Registry::get('Zend_Config');

        $plugin = 'MAPI_' . $options['movie_plugin'];

        $api = new $plugin();

        $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
        if(isset($options['proxy'])){
            $api_params['proxy'] = $options['proxy'];
        }

        $api->setParams($api_params);
        $myArrayofData = $api->getMovieDetails($params['api_id']);

        $this->_helper->json($myArrayofData);
    }

    /**
     * api_id et api_name
     * OU
     * db_id
     *
     * ex: 121734 : Las aventuras de Tadeo Jones
     *
     * http://localhost/mediaglobe/media/addmovie/api_name/tmdb/api_id/121734
     *
     * 72105
     *
     * http://localhost/mediaglobe/media/addmovie/db_id/7
     */
    public function addmovieAction() {

        try {
            $returnSuccess = false;
            $returnmessage = '';
            $return = null;

            $params = $this->_request->getParams();

            if (isset($params['movieIdInDB']))
                $return = $this->add_db_movie($params['movieIdInDB']);
            elseif (isset($params['api_name']) && isset($params['api_id']))
                $return = $this->add_api_movie($params['api_name'], $params['api_id']);
            else {
                $this->_response->clearBody();
                $this->_response->clearHeaders();
                $this->_response->setHttpResponseCode(406);
            }
        }
        catch (Exception $e) {
            $returnmessage = "Erreur: exception";
        }

        if (!$return)
            $return = array('success' => $returnSuccess, 'message' => $returnmessage);
        $this->_helper->json($return);
    }

    /**
     *
     * @param unknown_type $api_name
     * @param unknown_type $api_id
     */
    private function add_api_movie($api_name, $api_id) {

        $returnSuccess = false;
        $returnmessage = '';

        $movieMapper = new App_Model_Map_Movie();

        $idUser = $this->_sessionManager->getUserId();

        // verifier si le film est en base
        $idMovie = $movieMapper->getMovieIdByAPI($api_name, $api_id);

        if ($idMovie == -1) { // si le film n'est pas en base

            //    rechercher les details
            $options = Zend_Registry::get('Zend_Config');
            $plugin = 'MAPI_' . $options['movie_plugin'];
            $api_params['lang'] = substr($options['defaultLocale'], 0, 2);
            $api_params['proxy'] = (isset($options['proxy']) ? $options['proxy'] : '');
            $api  = new $plugin();
            $api->setParams($api_params);
            $movieDetails = $api->getMovieDetails($api_id); // MAPI_Model_Movie

            // add movie
            $name = $movieDetails->o_title;
            $nameFr = $movieDetails->o_title;
            $urlPicture = $movieDetails->poster;
            $rating = 0;
            $dateOut = $movieDetails->production_year;
            $createdBy = -1;
            $description = $movieDetails->plot;
            $api_name = 'TMDB';
            $api_idMovie = $movieDetails->id;
            $movieMapper->addMovie($name, $nameFr, $urlPicture, $rating, $dateOut, $createdBy, $description, $api_name, $api_idMovie);

            // recup id
            $idMovie = $movieMapper->getMovieIdByAPI($api_name, $api_id);
            if ($idMovie == -1)
                $returnmessage = 'film non trouvé';
            else {
                //    ajouter rt_user_movie
                $movieMapper->linkUserToMovie($idUser, $idMovie);
                $returnSuccess = true;
            }
        }
        else { // si le film est deja en base
            // verifier si le lien est en base
            if ($movieMapper->linkExists($idUser, $idMovie))
                $returnmessage = 'lien non trouvé';
            else {
                //    ajouter rt_user_movie
                $movieMapper->linkUserToMovie($idUser, $idMovie);
                $returnSuccess = true;
            }
        }

        return array('success' => $returnSuccess, 'message' => $returnmessage);
    }

    /**
     *
     * @param unknown_type $idMovie
     */
    private function add_db_movie($idMovie) {

        $returnSuccess = false;
        $returnmessage = '';

        $movieMapper = new App_Model_Map_Movie();

        $idUser = $this->_sessionManager->getUserId();

        // verifier si le film est en base
        if (!$movieMapper->movieExists($idMovie))
            $returnmessage = 'le film n\'existe pas';
        else {
            // verifier si le lien est en base
            if ($movieMapper->linkExists($idUser, $idMovie))
                $returnmessage = 'le lien existe deja';
            else {
                // ajouter rt_user_movie
                $movieMapper->linkUserToMovie($idUser, $idMovie);
                $returnSuccess = true;
            }
        }

        array('success' => $returnSuccess, 'message' => $returnmessage);
    }
}

